// RotatingTriangle.js
// Vertex shader 顶点着色器
var VSHADER_SOURCE = 
  "attribute vec4 a_Position;\n" + 
  "uniform mat4 u_ModelMatrix;\n" + 
  "void main() {\n" + 
  " gl_Position = u_ModelMatrix * a_Position;\n" + 
  "}\n";

// Fragment shader 片段着色器
// 注意：只能指定float类型的attribute变量，但是uniform变量可以是任意类型的，所以使用前需要指定uniform变量的类型
var FSHADER_SOURCE = 
  "precision mediump float;\n" + 
  "uniform vec4 u_FragColor;\n" + 
  "void main() {\n" + 
  " gl_FragColor = u_FragColor;\n" + 
  "}\n";

var DEBUG = true;
var ANGLE_STEP = 60.0;
var g_last = Date.now();
var g_frame = 0;
var FRAME_SAMPLE_INTERVAL = 10;

function onBtnUpClick() {
  ANGLE_STEP += 10.0;
  if (ANGLE_STEP >= 360.0) {
    ANGLE_STEP = 350.0;
  }
}

function onBtnDownClick() {
  ANGLE_STEP -= 10.0;
  if (ANGLE_STEP <= 0.0) {
    ANGLE_STEP = 5.0;
  }
}

function main() {
  var canvas = document.getElementById("webgl");

  var gl = getWebGLContext(canvas);
  if (!gl) {
    console.log("Failed to get the rendering context for WebGL");
    return;
  }

  if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
    console.log("Fialed to initialize shaders.");
    return;
  }

  gl.clearColor(0.0, 0.0, 0.0, 1.0);

  setUniform4f(gl, "u_FragColor", 1.0, 0.0, 0.0, 1.0);

  // 设置顶点信息
  var n = initVertexBuffers(gl);
  if (n < 0) {
    console.log("Failed to set the position of the vertices.");
    return;
  }

  var currentAngle = 0.0;
  var matrix = new Matrix4();

  var u_ModelMatrix = gl.getUniformLocation(gl.program, "u_ModelMatrix");
  if (u_ModelMatrix < 0) {
    return;
  }

  if (DEBUG) {
    var frameEle = document.getElementById("frame");
  }

  var i = 0;
  var tick = function () {
    currentAngle = animate(currentAngle);
    draw(gl, n, currentAngle, matrix, u_ModelMatrix);
    requestAnimationFrame(tick);

    ++i;
    if (i === FRAME_SAMPLE_INTERVAL) {
      i = 0;
      frameEle.innerHTML = Math.floor(g_frame / FRAME_SAMPLE_INTERVAL);
      g_frame = 0;
    }
  };

  tick();
}

function initVertexBuffers(gl) {
  var vertices = new Float32Array(
    [
      -0.5, -0.5, 
      0.5, -0.5,
      0, 0.5
    ]);
  var n = 3;

  // 创建缓冲区对象
  var vertexBuffer = gl.createBuffer();
  // gl.deleteBuffer(vertexBuffer);
  if (!vertexBuffer) {
    console.log("Failed to create the buffer object.");
    return -1;
  }

  // 绑定缓冲区对象
  gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
  // 缓冲区对象写入数据
  gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);

  var a_Position = gl.getAttribLocation(gl.program, "a_Position");
  if (a_Position < 0) {
    console.log("Failed to get the storage location of a_Position");
    return -1;
  }

  // 将缓冲区对象分配给a_Position对象
  gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 0, 0);
  // 连接a_Position变量与分配给它的缓冲区对象
  gl.enableVertexAttribArray(a_Position);
  // gl.disableVertexAttribArray(a_Position);

  return n;
}

function draw(gl, n, currentAngle, matrix, u_ModelMatrix) {
  matrix.setRotate(currentAngle, 0, 0, 1);

  gl.uniformMatrix4fv(u_ModelMatrix, false, matrix.elements);

  gl.clear(gl.COLOR_BUFFER_BIT);

  gl.drawArrays(gl.TRIANGLES, 0, n);
}

function animate(angle) {
  var now = Date.now();
  var elapsed = now - g_last;
  g_last = now;

  var newAngle = angle + (ANGLE_STEP * elapsed) / 1000.0;

  if (DEBUG) {
    g_frame += (1000.0 / elapsed);
  }

  return newAngle %= 360;
}
